"""
    组织
"""

from rest_framework.views import APIView
from users.serialiaers.organization import OrganizationUserTreeSerializer, OrganizationModelSerializer, OrganizationModelRetrieveSerializer
from utils.tree import TreeAPIView, TreeAPIFormView
from utils.json_response import JsonResponse
from utils.model_view_set import CustomModelViewSet
from users.models import Organization


class OrganizationTreeView(TreeAPIView):
    """
        组织架构目录树
    """
    queryset = Organization.objects.all()


class OrganizationRoleTreeView(APIView):
    """
        组织架构关联角色树
    """

    def get(self, request):
        organizations = Organization.objects.all()
        serializer = OrganizationUserTreeSerializer(organizations, many=True)
        tree_dict = {}
        tree_data = []
        for item in serializer.data:
            new_item = {
                'id': item['id'],
                'label': item['label'],
                'pid': item['pid'],
                'children': item['children']
            }
            tree_dict[item['id']] = new_item
        for i in tree_dict:
            if tree_dict[i]['pid']:
                pid = tree_dict[i]['pid']
                parent = tree_dict[pid]
                parent['children'].append(tree_dict[i])
            else:
                tree_data.append(tree_dict[i])
        return JsonResponse(data=tree_data, code=200)


class OrganizationModelView(TreeAPIFormView, CustomModelViewSet):
    """
    权限管理：增删改查
    """
    perms_map = ({'*': 'admin'}, {'*': 'organization_all'}, {'get': 'organization_list'}, {'put': 'organization_edit'},
                 {'post': 'organization_create'}, {'delete': 'organization_delete'})
    queryset = Organization.objects.all()
    serializer_class = OrganizationModelSerializer
    search_fields = ('name', 'type',)  # 已在全局设置：指定字段模糊搜索

    def get_serializer_class(self):
        # 根据请求类型动态变更serializer
        if self.action == 'retrieve':
            return OrganizationModelRetrieveSerializer
        return OrganizationModelSerializer
